package com.salesmanager.core.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Liutong on 2016/6/2.
 */
public class ReaderXmlForDOMUtil {

    private static final Logger log = LoggerFactory.getLogger(ReaderXmlForDOMUtil.class);

    public static Map readerXml(String xml) {
        Map<String, Object> map = new HashMap<String, Object>();

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory
                    .newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder
                    .parse(new InputSource(new StringReader(xml)));

            Element root = doc.getDocumentElement();
            NodeList books = root.getChildNodes();
            if (books != null) {
                for (int i = 0; i < books.getLength(); i++) {
                    Node book = books.item(i);
                    if (book.getFirstChild() != null) {
                        map.put(book.getNodeName(), book.getFirstChild().getNodeValue());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }


    public static void main(String[] args) {
        String xml =
                "<xml>" +
                        "<return_code><![CDATA[SUCCESS]]></return_code>" +
                        "<return_msg><![CDATA[]]></return_msg>" +
                        "<mch_appid><![CDATA[wx825ccde0759ed97e]]></mch_appid>" +
                        "<mchid><![CDATA[1340116401]]></mchid>" +
                        "<device_info></device_info>" +
                        "<nonce_str><![CDATA[xm9m20160603105054]]></nonce_str>" +
                        "<result_code><![CDATA[SUCCESS]]></result_code>" +
                        "<partner_trade_no><![CDATA[order20160603105054]]></partner_trade_no>" +
                        "<payment_no><![CDATA[1000018301201606030468560638]]></payment_no>" +
                        "<payment_time><![CDATA[2016-06-03 10:50:56]]></payment_time>" +
                        "</xml>";

        Map map = ReaderXmlForDOMUtil.readerXml(xml);

        System.out.println(map);
    }
}
